<template>
  <div class="app-container">
    <div class="settle-manage">
      <el-form :inline="true" :model="dataFilter" class="search-form">
        <el-form-item label="设备类型" prop="equipType" class="form-item-wrapper">
          <el-select v-model="dataFilter.equipType" clearable placeholder="请选择" style="width: 120px">
            <el-option v-for="item in equipOption" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属商户" class="form-item-wrapper">
          <el-select v-model="dataFilter.tenantId" placeholder="请选择所属商户" clearable style="width: 200px"
            @change="loadLocationData" filterable remote :remote-method="searchMerchant">
            <el-option v-for="item in merchantList" :key="item.id" :label="item.tenantName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在地点位置" class="form-item-wrapper">
          <el-tree-select v-model="dataFilter.locationIds" :data="fullLocationTree" multiple collapse-tags
            collapse-tags-tooltip :render-after-expand="false" show-checkbox :filter-node-method="filterNodeMethod"
            filterable node-key="id" value-key="id" :props="locationTreeProps" @check="loadEnterpriseData"
            placeholder="请选择所在地点位置" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="企业简称" class="form-item-wrapper">
          <el-select v-model="dataFilter.enterpriseIds" multiple collapse-tags collapse-tags-tooltip clearable
            placeholder="请选择企业简称" style="width: 200px" filterable remote :remote-method="searchEnterprise">
            <el-option v-for="item in enterpriseList" :key="item.id" :label="item.shortName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" class="form-item-wrapper">
          <el-input v-model="dataFilter.equipName" placeholder="请输入设备名称" style="width: 200px" />
        </el-form-item>
        <el-form-item label="设备编号" class="form-item-wrapper">
          <el-input v-model="dataFilter.equipNum" placeholder="请输入设备编号" style="width: 280px" />
        </el-form-item>
        <el-form-item label="开始日期" class="form-item-wrapper">
          <el-date-picker v-model="dataFilter.startDate" type="date" clearable format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" placeholder="选择开始日期" style="width: 150px" />
        </el-form-item>
        <el-form-item label="结束日期" class="form-item-wrapper">
          <el-date-picker v-model="dataFilter.endDate" type="date" clearable format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" placeholder="选择结束日期" style="width: 150px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom: 20px;display: flex;justify-content: start;">
        <el-button type="primary" @click="handleAdd">添加</el-button>
        <el-upload ref="waterUploadRef" :auto-upload="false" :show-file-list="false" :on-change="handleWaterFileChange"
          accept=".xlsx,.xls" style="display: inline-block; margin-left: 10px;">
          <el-button type="success">导入水表数据</el-button>
        </el-upload>
        <el-upload ref="elecUploadRef" :auto-upload="false" :show-file-list="false" :on-change="handleElecFileChange"
          accept=".xlsx,.xls" style="display: inline-block; margin-left: 10px;">
          <el-button type="success">导入电表数据</el-button>
        </el-upload>
        <el-button type="danger" @click="handleDownload" style="display: inline-block; margin-left: 10px;">
          导出全部数据
        </el-button>
      </div>
      <el-table :data="sourceData.list" border highlight-current-row stripe v-loading="loading">
        <el-table-column label="设备类型" header-align="center" align="center" width="100">
          <template #default="{ row }">
            <span>{{ row.equipType == 1 ? '电表' : '水表' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备名称" prop="equipName" header-align="center" />
        <el-table-column label="设备编号" prop="equipNum" header-align="center" />
        <el-table-column label="设备数据值" prop="equipDataValue" header-align="center" width="250" align="center">
          <template #default="{ row }">
            <span>{{ row.equipType == 1 ? row.equipDataValue + ' kW·h' : row.equipDataValue + ' t' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="采集时间" prop="collectTime" header-align="center" width="250" align="center" />
        <el-table-column label="是否计费配置" prop="billingSetting" header-align="center" width="130" align="center" />
        <el-table-column label="操作" align="center" width="180" header-align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              详情
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)" v-if="!(row.status==1)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :pageProps="pageProps" layout="prev, pager, next" @current-change="getList" />
    </div>
  </div>

  <CollectDataDialog ref="dialog" @listChange="itemData" />
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, UploadFile } from "element-plus";
import { getEquipCollectDataList, deleteEquipCollectData, importEquipCollectData,
  getMerchantByName, getLocationTree, getEnterpriseList, downloadDataImportTemplate } from "@/api/settle";
import Pagination from "@/components/Pagination/Index.vue";
import CollectDataDialog from "./components/CollectDataDialog.vue";
import { LocationTreeNode } from '@/api/types/location'

const loading = ref(false)
const dataFilter = reactive({
  equipType: null,
  tenantId: null,
  locationIds: [],
  enterpriseIds: [],
  equipName: '',
  equipNum: '',
  startDate: '',
  endDate: '',
});

const equipOption = ref<any>([
  { name: '电表', value: 1 },
  { name: '水表', value: 2 },
])

// 页面加载时获取商户列表
onMounted(() => {
  getList();
});

const pageProps = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const sourceData = reactive({
  list: [] as any[],
});

const getList = () => {
  let requestData = {
    pageNum: pageProps.value.pageNum,
    pageSize: pageProps.value.pageSize,
    ...dataFilter
  }
  if (dataFilter.startDate) {
    requestData.startDate = dataFilter.startDate + ' 00:00:00';
  }
  if (dataFilter.endDate) {
    requestData.endDate = dataFilter.endDate + ' 23:59:59';
  }
  loading.value = true
  getEquipCollectDataList(requestData)
  .then((res: any) => {
    loading.value = false
    if (res.success) {
      sourceData.list = res.data.records || [];
      pageProps.value.total = res.data.total || 0;
    } else {
      sourceData.list = [];
      pageProps.value.total = 0;
    }
  })
  .catch((err: any) => {
    loading.value = false
    console.error("err", err);
    sourceData.list = [];
    pageProps.value.total = 0;
  });
};

const handleSearch = () => {
  pageProps.value.pageNum = 1; // 搜索时重置到第一页
  getList();
};

const onReset = () => {
  dataFilter.equipType = null;
  dataFilter.tenantId = null,
  dataFilter.locationIds = [],
  dataFilter.enterpriseIds = [],
  dataFilter.equipName = '',
  dataFilter.equipNum = '';
  dataFilter.startDate = '';
  dataFilter.endDate = '';
  Object.assign(pageProps.value, {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  getList(); // 重置后重新获取数据
};

const dialog = ref<any>(null);

const handleAdd = () => {
  dialog.value.dialogVisible = true;
  dialog.value.dialogStatus = "create";
  dialog.value.isDisabled = true;
};

const handleView = (row: any) => {
  dialog.value.dialogVisible = true;
  dialog.value.dialogStatus = "view";
  dialog.value.isDisabled = false;
  nextTick(() => {
    // 先重置表单
    dialog.value.reset();
    // 然后设置数据
    Object.assign(dialog.value.tableItem, row);
  });
};

const handleEdit = (row: any) => {
  console.log("row", row);
  dialog.value.dialogVisible = true;
  dialog.value.dialogStatus = "edit";
  dialog.value.isDisabled = true;
  nextTick(() => {
    // 先重置表单
    dialog.value.reset();
    // 然后设置数据
    Object.assign(dialog.value.tableItem, row);
  });
};

const itemData = () => {
  getList();
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    "确定要删除吗?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
  .then(() => {  
    // 单个删除，使用路径参数
    deleteEquipCollectData(row.id)
    .then((res: any) => {
      ElMessage.success("删除成功！");
      getList();
    })
    .catch((err: any) => {
      console.error("err", err.msg);
      ElMessage.error("删除失败！");
    });
  })
  .catch((err: any) => {
    console.error("删除采集数据失败:", err);
  });
};

// 上传相关
const waterUploadRef = ref();
const elecUploadRef = ref();

// 处理水表数据文件选择
const handleWaterFileChange: UploadProps['onChange'] = (file: UploadFile) => {
  if (!file.raw) {
    return;
  }
  
  // 验证文件类型
  const fileName = file.name;
  const fileExt = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
  if (fileExt !== '.xlsx' && fileExt !== '.xls') {
    ElMessage.error('只能上传 Excel 文件！');
    return;
  }
  
  // 验证文件大小（限制为20MB）
  const fileSize = file.size || 0;
  if (fileSize > 20 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过 20MB！');
    return;
  }
  
  // 创建 FormData 对象
  const formData = new FormData();
  formData.append('file', file.raw);
  formData.append('equipType', '2'); // 2 表示水表
  
  importEquipCollectData(formData).then((res: any) => {
    ElMessage.success('导入水表数据成功！');
    getList();
    waterUploadRef.value?.clearFiles();
  }).catch((err: any) => {
    ElMessage.error(err.msg || '导入水表数据失败！');
  });
};

// 处理电表数据文件选择
const handleElecFileChange: UploadProps['onChange'] = (file: UploadFile) => {
  if (!file.raw) {
    return;
  }
  
  // 验证文件类型
  const fileName = file.name;
  const fileExt = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
  if (fileExt !== '.xlsx' && fileExt !== '.xls') {
    ElMessage.error('只能上传 Excel 文件！');
    return;
  }
  
  // 验证文件大小（限制为20MB）
  const fileSize = file.size || 0;
  if (fileSize > 20 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过 20MB！');
    return;
  }
  
  // 创建 FormData 对象
  const formData = new FormData();
  formData.append('file', file.raw);
  formData.append('equipType', '1'); // 1 表示电表
  
  importEquipCollectData(formData).then((res: any) => {
    ElMessage.success('导入电表数据成功！');
    getList();
    elecUploadRef.value?.clearFiles();
  }).catch((err: any) => {
    ElMessage.error(err.msg || '导入电表数据失败！');
  });
};

// 商户列表
const merchantList = ref<any[]>([]);

// 获取商户列表
const getMerchantList = (name?: string) => {  
  // 使用新的按名称查询接口
  getMerchantByName(name).then((res: any) => {
    if (res.success && res.data) {
      merchantList.value = Array.isArray(res.data) ? res.data : []
    } else {
      console.warn('未获得到商户列表:', res)
      merchantList.value = []
    }
  }).catch((err: any) => {
    console.error('获取商户列表失败', err)    
  })
};

const searchMerchant = (name: string) => {
  getMerchantList(name)
}

// 地点位置数据
const fullLocationTree = ref<LocationTreeNode[]>([])
const locationTreeProps = ref({
  label: 'name'
});

// 加载地点位置数据
const loadLocationData = async () => {
  try {
    if (!dataFilter.tenantId) {
      fullLocationTree.value = []
      return
    }
    enterpriseList.value = []
    loadEnterpriseData()
    
    const res = await getLocationTree(dataFilter.tenantId)
    if (res.success && res.data) {
      fullLocationTree.value = res.data
    } else {
      const errorMsg = res.msg || '加载地点位置数据失败'
      ElMessage.error(`加载失败: ${errorMsg}`)
      fullLocationTree.value = []
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请检查网络连接后重试')
    fullLocationTree.value = []
  }
}

const filterNodeMethod = (value: string, data: any) => {
  return value ? data.name.includes(value) : true;
}

// 企业列表
const enterpriseList = ref<any[]>([]);

// 加载企业数据
const loadEnterpriseData = async () => {
  let requestData = {
    tenantId: dataFilter.tenantId,
    locationIds: dataFilter.locationIds,
  }
  doGetEnterpriseList(requestData)
}

// 搜索企业数据
const searchEnterprise = async (shortName: string) => {
  let requestData = {
    shortName: shortName,
    tenantId: dataFilter.tenantId,
    locationIds: dataFilter.locationIds,
  }
  doGetEnterpriseList(requestData)
}

const doGetEnterpriseList = (requestData: any) => {
  getEnterpriseList(requestData).then((res: any) => {
    if (res.success && res.data) {
      enterpriseList.value = Array.isArray(res.data) ? res.data : []
    } else {
      enterpriseList.value = []
    }
  }).catch((err: any) => {
    console.error('获取企业列表失败', err)
  })
}

const handleDownload = async () => {
  if (!dataFilter.equipType) {
    ElMessage.error('请选择设备类型！');
    return;
  }
 
  downloadDataImportTemplate(dataFilter)
}

</script>

<style lang="scss" scoped>
.app-container {
  flex: 1;
}

.form-item-wrapper {
  margin-right: 10px;
}
</style>